//
//  EFADangerVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/11/7.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFADangerVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "ApiManager.h"
#import "EFADangerTCell.h"
#import "EFAModel.h"
#import "UIColor+XDHex.h"
#import "GlobalHeader.h"
#import "KSPhotoBrowser.h"
#import "EFADangerAddVC.h"

@interface EFADangerVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFADangerTCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) UIBarButtonItem *filterBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *publishBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *editBarBtnItem;

@property (strong, nonatomic) NSArray *typeArray;
@property (assign, nonatomic) NSInteger currentTypeId;
@property (nonatomic, strong) EFADangerListModel *dangerModel;
@end

static NSString *const kReuseCellId = @"EFADangerTCell";
static NSInteger const kRequestSize = 20;

@implementation EFADangerVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initLogicData];
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}
- (void)initLogicData {
    if (self.dangerItem) {
        self.dangerModel = [[EFADangerListModel alloc] initWithDangerListItem:self.dangerItem];
    }
    self.currentTypeId = 2;
}
- (void)initNavigationBar {
    self.navigationItem.title = self.dangerItem ? self.dangerItem.efairyproject_name : @"隐患曝光";
    
    NSInteger roleLevel = [EFAModel sharedInstance].loginInfo.user_info.efairyrole_level;
    if (self.dangerItem) {
        if (roleLevel <= EFALoginUserRoleAdmin) {
            self.navigationItem.rightBarButtonItem = self.dangerItem.efairyhiddendanger_is_fixed ? nil : self.editBarBtnItem;
        }
    } else {
        if (roleLevel <= EFALoginUserRoleAdmin) {
            self.navigationItem.rightBarButtonItems = @[self.publishBarBtnItem, self.filterBarBtnItem];
        } else {
            self.navigationItem.rightBarButtonItem = self.filterBarBtnItem;
        }
    }
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}
- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    if (!self.dangerItem) {
        self.tableView.mj_header = self.mj_header;
        self.tableView.mj_footer = self.mj_footer;
        [self.tableView.mj_header beginRefreshing];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有隐患" attributes:dic];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dangerModel.hiddendanger_list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFADangerTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.dangerModel.hiddendanger_list.count) {
        [cell configViewWithDangerListItem:self.dangerModel.hiddendanger_list[indexPath.row]];
    }
    cell.delegate = self;
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 9.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (!self.dangerItem && indexPath.row < self.dangerModel.hiddendanger_list.count) {
        EFADangerListItem *item = self.dangerModel.hiddendanger_list[indexPath.row];
        [self jumpToDangerDetailWithDangerItem:item];
    }
}
#pragma mark - EFADangerTCellDelegate
- (void)dangerTCell:(EFADangerTCell *)cell imgViewTapped:(NSArray<UIImageView *> *)imgViewArray indexPath:(NSIndexPath *)cIndexPath {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.row >= self.dangerModel.hiddendanger_list.count) {
        return;
    }
    EFADangerListItem *item = self.dangerModel.hiddendanger_list[indexPath.row];
    if (cIndexPath.row >= item.efairyhiddendanger_imgurl_list.count) {
        return;
    }
    
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:item.efairyhiddendanger_imgurl_list.count];
    [item.efairyhiddendanger_imgurl_list enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImageView *tempImgView = nil;
        if (idx < imgViewArray.count) {
            tempImgView = imgViewArray[idx];
        }
        KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:tempImgView imageUrl:[NSURL URLWithString:obj]];
        [mArray addObject:photoItem];
    }];
    [self showPhotoBrowser:mArray selectedIndex:cIndexPath.row];
}

#pragma mark - event response
- (void)publishBarBtnTapped:(UIBarButtonItem *)item {
    EFADangerAddVC *vc = [[EFADangerAddVC alloc] init];
    vc.successHandle = ^{
        [self.tableView.mj_header beginRefreshing];
    };
    [self showViewController:vc sender:nil];
}
- (void)filterBarBtnTapped:(UIBarButtonItem *)item {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (NSDictionary *dic in self.typeArray) {
        [alertVC addAction:[UIAlertAction actionWithTitle:dic[@"typeName"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.currentTypeId = [dic[@"typeId"] integerValue];
            [self.tableView.mj_header beginRefreshing];
        }]];
    }
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)editBarBtnItemTapped:(UIBarButtonItem *)item {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"隐患确定已经排查了吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestEditDanger];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
#pragma mark - private methods
- (void)showPhotoBrowser:(NSArray<KSPhotoItem *> *)photoItems selectedIndex:(NSUInteger)index {
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:photoItems selectedIndex:index];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleNone;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}
- (void)jumpToNoticeDetailWitNotItem:(EFANotListItem *)item indexPath:(NSIndexPath *)indexPath {
    //    EFANoticeDetailVC *vc = [[EFANoticeDetailVC alloc] init];
    //    vc.noticeItem = item;
    //    vc.successDelHandle = ^{
    //        [self.noticeModel removeNotListItem:item];
    //        [self refreshWholeView];
    //    };
    //    [self showViewController:vc sender:nil];
}
- (void)jumpToDangerDetailWithDangerItem:(EFADangerListItem *)item {
    EFADangerVC *vc = [[EFADangerVC alloc] init];
    vc.dangerItem = item;
    vc.successHandle = ^{
        [self refreshWholeView];
    };
    [self showViewController:vc sender:nil];
}
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.dangerModel.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    self.tableView.mj_footer.hidden = self.dangerModel.totalZero;
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestDangerListWithHeader:isHeader];
}

- (EFADangerListModel *)dangerModelWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.dangerModel;
    }
    
    EFADangerListModel *temp = [EFADangerListModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    if (!temp) {
        return self.dangerModel;
    }
    
    if (AddMore && self.dangerModel) {
        [self.dangerModel addMoreWithData:temp];
    } else {
        self.dangerModel = temp;
    }
    return self.dangerModel;
}
- (void)exitViewController {
    if (self.successHandle) {
        self.successHandle();
        self.successHandle = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - network request
- (void)requestDangerListWithHeader:(BOOL)isHeader {
    // 需要登录
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.dangerModel.hiddendanger_list.lastObject.efairyhiddendanger_id;
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           //                           @"keyword" : @"",
                           @"efairyhiddendanger_is_fixed" : @(self.currentTypeId),
                           @"last_id" : @(last_id),
                           @"size" : @(kRequestSize)};

    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDangerList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求维护记录列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        [self dangerModelWithDictionary:responseObject isAddMore:!isHeader];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求维护记录列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

- (void)requestEditDanger {
    // 发布帖子
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    self.dangerItem.efairyhiddendanger_is_fixed = 1;
    self.dangerItem.efairyuser_nickname_fixed_user = [EFAModel sharedInstance].loginInfo.user_info.efairyuser_nickname;
    NSMutableDictionary *pubDic = [self.dangerItem yy_modelToJSONObject];
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyhiddendanger_info" : pubDic};
    
    NSLog(@"编辑隐患的请求参数：%@", pars);
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiDanger] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"编辑隐患返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        MBProgressHUD *temp = [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"排查成功"];
        temp.completionBlock = ^{
            [self exitViewController];
        };
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"编辑隐患失败：%@", error);
        self.dangerItem.efairyhiddendanger_is_fixed = 0;
        [hud hideAnimated:NO];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)publishBarBtnItem {
    if (!_publishBarBtnItem) {
        _publishBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"app_danger_add"] style:UIBarButtonItemStylePlain target:self action:@selector(publishBarBtnTapped:)];
    }
    return _publishBarBtnItem;
}
- (UIBarButtonItem *)filterBarBtnItem {
    if (!_filterBarBtnItem) {
        _filterBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"msg_filter"] style:UIBarButtonItemStylePlain target:self action:@selector(filterBarBtnTapped:)];
    }
    return _filterBarBtnItem;
}
- (UIBarButtonItem *)editBarBtnItem {
    if (!_editBarBtnItem) {
        _editBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"排查" style:UIBarButtonItemStylePlain target:self action:@selector(editBarBtnItemTapped:)];
        NSDictionary * barItemAttributes = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_editBarBtnItem setTitleTextAttributes:barItemAttributes forState:UIControlStateNormal];
        NSDictionary * disableBarItemAtt = @{NSForegroundColorAttributeName: [UIColor xd_colorWithHex:EFAGlobalColorDarkGreen alpha:0.5],
                                             NSFontAttributeName: [UIFont systemFontOfSize:15]};
        [_editBarBtnItem setTitleTextAttributes:disableBarItemAtt forState:UIControlStateDisabled];
    }
    return _editBarBtnItem;
}
- (NSArray *)typeArray {
    if (!_typeArray) {
        _typeArray = @[@{@"typeId" : @(0), @"typeName" : @"隐患未排查"},
                       @{@"typeId" : @(1), @"typeName" : @"隐患已排查"},
                       @{@"typeId" : @(2), @"typeName" : @"全部"}];
    }
    return _typeArray;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
//        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
